package com.bee.剑指offer;

import java.util.Arrays;

public class 排序 {

    public static int[] MySort(int[] arr) {
        quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
        return arr;
    }

    private static void quickSort(int[] arr, int left, int right) {
        if (arr == null || arr.length <= 0 || left >= right) {
            return;
        }
        int base = arr[left];
        int low = left;
        int high = right;
        while (low != high) {
            while (low < high && arr[high] >= base) {
                high--;
            }
            while (low < high && arr[low] <= base) {
                low++;
            }
            // 从右边检索找到了比base小的，从左边检索扎到了比base大的，此时low,high都停下来了，交换
            int temp = arr[high];
            arr[high] = arr[low];
            arr[low] = temp;
        }
        // low = high，两指针相遇，可以将base和相遇的地方进行交换
        arr[left] = arr[low];
        arr[low] = base;

        // 在检索左边区间，之后检索右边区间
        quickSort(arr, left, low - 1);
        quickSort(arr, low + 1, right);
    }

    public static void main(String[] args) {
        MySort(new int[]{5, 2, 3, 1, 4});
    }
}
